<?php

namespace IDock\Insurance\QHIC\Request;

use GuzzleHttp\Psr7\Stream;
use IDock\Http\RequestFormat;
use IDock\IDock\IDockEnums;
use IDock\Insurance\QHIC\QHICEnums;
use IDock\Insurance\QHIC\Request\AllQHICRequest;
use IDock\Insurance\QHIC\Response\UploadFileResponse;
use IDock\Visitor\Premium\PremiumInquiryVisitor;
use IDock\Visitor\UploadFileVisitor;

class UploadFileRequest extends AllQHICRequest
{
    public $requestType = 'VHL0006';

    protected $response = UploadFileResponse::class;

    protected $urlTip = '影像上传';

    protected $inLog = true;

    /**
     * @var  UploadFileVisitor $visitor
     */
    protected $visitor;

    public function generate(): array
    {

        return [
            'CAppNo' => $this->visitor->biInquiryNo ?: $this->visitor->ciInquiryNo,
            'ImgList' => $this->imageList()
        ];
    }

    private function imageList(): array
    {
        $list = [];
        $group = [];
        foreach ($this->visitor->getFileList() as $file){
            $key = QHICEnums::$fileType[$file['type']] ??'';
            $group[$key][] = $file;
        }
        foreach ($group as $key => $fileList) {
            $img = [
                'CImgTyp' => $key,
                'files' => [],
                'CActionTyp' => 'A'
            ];
            foreach ($fileList as $file){
                if (!$file['url'] ?? '') {
                    continue;
                }
                $baseName = basename($file['url']);
                $extArr = explode('.',$baseName);
                $ext = end($extArr);
                $img['files'][] = [
                    'fileName' => date('YmdHis').'-'.substr(sha1(mt_rand(100000,999999)),0,6).'.'.$ext,
                    'base64Img' => $file['url']
                ];
            }
            $list[] = $img;
            unset($img);
        }

        return $list;
    }
}
